package com.ly.lypicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ly.lypicturebackend.exception.ErrorCode;
import com.ly.lypicturebackend.exception.ThrowUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author luyi
 * @create 2025-02-20-1:11
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtil.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件为空");
        //校验文件大小
        final long maxSize = 1024 * 1024;
        long size = multipartFile.getSize();
        ThrowUtil.throwIf(size > 2 * maxSize, ErrorCode.PARAMS_ERROR, "文件过大,最大为2M");
        //校验文件类型
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        List<String> ALLOW_SUFFIX = Arrays.asList("jpg", "jpeg", "png", "gif", "webp");
        ThrowUtil.throwIf(!ALLOW_SUFFIX.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }
}
